package cn.leftshine.myithome;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.res.ColorStateList;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.v4.widget.NestedScrollView;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.view.menu.MenuBuilder;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.util.TypedValue;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.webkit.JavascriptInterface;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.Date;

import cn.leftshine.myithome.utils.DateTool;
import cn.leftshine.myithome.utils.HTMLTool;

import static cn.leftshine.myithome.utils.ImgTool.tintDrawable;

public class NewsDetailActivity extends AppCompatActivity {

    private WebView webView;
    private TextView tv_newsInfo_date,tv_newsInfo_source,tv_newsInfo_original,tv_newsInfo_author,tv_newsInfo_title,tv_newsInfo_toolbar_title;
    private ImageButton ib_newsDetail_collect;
    private CollapsingToolbarLayout cToolBar_newsInfo;
    private NestedScrollView news_detail_nestedScrollView;
    private AppBarLayout appbar;
    private RelativeLayout rl_newsDetail_bottomBar,progress_layer;
    private LinearLayout ll_news_detail_news_content;
    private boolean isTitleShow=false;
    private boolean isBottomBarShow=true;
    private boolean isCollected = false;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            Window window = getWindow();
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS
                    | WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
            window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            //获取样式中的属性值
            TypedValue typedValue = new TypedValue();
            this.getTheme().resolveAttribute(android.R.attr.colorPrimary, typedValue, true);
            int[] attribute = new int[] { android.R.attr.colorPrimary };
            TypedArray array = this.obtainStyledAttributes(typedValue.resourceId, attribute);
            int color = array.getColor(0, Color.TRANSPARENT);
            array.recycle();

            window.setStatusBarColor(color);
        }
        setContentView(R.layout.activity_news_detail);
        bindViews();
        Intent intent = getIntent();
        String title = intent.getStringExtra("title");
        String link = intent.getStringExtra("link");
        String pubDate = intent.getStringExtra("pubDate");
        String content = intent.getStringExtra("content");
        getSupportActionBar().setTitle(title);
        getSupportActionBar().setDisplayShowTitleEnabled(false);
        cToolBar_newsInfo.setTitle(title);
        tv_newsInfo_title.setText(title);
        tv_newsInfo_toolbar_title.setText(title);
        tv_newsInfo_toolbar_title.setAlpha(0);
        isTitleShow=false;
        //tv_newsInfo_toolbar_title.setVisibility(View.GONE);

        final Date isoDate = DateTool.isoStrParseToDate(pubDate);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        tv_newsInfo_date.setText(sdf.format(isoDate));
        //content=content.replace("<img", "<img height=\"100%\" width=\"250px\"");

        WebSettings webSettings = webView.getSettings();//获取webview设置属性
        webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);//把html中的内容放大webview等宽的一列中
        webSettings.setJavaScriptEnabled(true);//支持js
        //webSettings.setBuiltInZoomControls(true); // 显示放大缩小
        //webSettings.setSupportZoom(true); // 可以缩放
        webView.addJavascriptInterface(new JavaScriptInterface(this), "imagelistner");//这个是给图片设置点击监听的，如果你项目需要webview中图片，点击查看大图功能，可以这么添加
        webView.setWebViewClient(new MyWebViewClient());
        //content = "<link rel=\"stylesheet\" type=\"text/css\" href=\"https://m.ithome.com/staticfileunite/common_comment.min%7Ccommon_news-list.min%7Ccommon_user-menu.min%7Cnews.min%7Cruanmei-footer.min.css\" />"+content;\
        //content = "<link rel=\"stylesheet\" type=\"text/css\" href=\"html/css/news_detail.css\" />"+content;
        //content = cssSrc+content;
        String htmlData = HTMLTool.createHtmlDate(title,content,link);
        webView.loadDataWithBaseURL("file:///android_asset/html/", htmlData, "text/html" , "utf-8", null);
    }


    private void bindViews() {
        Toolbar toolbar = findViewById(R.id.toolbar_news_detail);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);//左侧添加一个默认的返回图标
        getSupportActionBar().setHomeButtonEnabled(true); //设置返回键可用

        webView= findViewById(R.id.wv_news_content);
        tv_newsInfo_date = findViewById(R.id.tv_newsInfo_date);
        tv_newsInfo_title = findViewById(R.id.tv_newsInfo_title);
        tv_newsInfo_toolbar_title = findViewById(R.id.tv_newsInfo_toolbar_title);
        /*tv_newsInfo_source = findViewById(R.id.tv_newsInfo_source);
        tv_newsInfo_original = findViewById(R.id.tv_newsInfo_original);
        tv_newsInfo_author = findViewById(R.id.tv_newsInfo_author);*/
        cToolBar_newsInfo =findViewById(R.id.cToolBar_newsInfo);
        news_detail_nestedScrollView  = findViewById(R.id.news_detail_nestedScrollView);
        rl_newsDetail_bottomBar = findViewById(R.id.rl_newsDetail_bottomBar);
        ib_newsDetail_collect = findViewById(R.id.ib_newsDetail_collect);
        progress_layer = findViewById(R.id.progress_layer);
        ll_news_detail_news_content = findViewById(R.id.ll_news_detail_news_content);

        ViewGroup.MarginLayoutParams vlp = (ViewGroup.MarginLayoutParams) tv_newsInfo_title.getLayoutParams();
        final int offsetValue =vlp.topMargin;
        appbar = findViewById(R.id.appbar);
        appbar.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
            @Override
            public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
                Log.i("pcj", "onOffsetChanged: verticalOffset="+verticalOffset);
                if (Math.abs(verticalOffset) <offsetValue&&isTitleShow) {
                        tv_newsInfo_toolbar_title.animate().alpha(0f).start();
                        isTitleShow=false;
                } else if (Math.abs(verticalOffset) >= offsetValue&&!isTitleShow) {
                        tv_newsInfo_toolbar_title.animate().alpha(1f).start();
                        isTitleShow = true;
                    }
            }
        });
        news_detail_nestedScrollView.setSmoothScrollingEnabled(true);
        news_detail_nestedScrollView.setOnScrollChangeListener(new NestedScrollView.OnScrollChangeListener() {
            @Override
            public void onScrollChange(NestedScrollView v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
                Log.i("pcj", "onScrollChange:" +
                        "\nonlyChildHeight="+ll_news_detail_news_content.getHeight() +
                        "\nscrollY+nestedScrollView.Height()="+(news_detail_nestedScrollView.getHeight()+scrollY) +
                        "\nscrollY-oldScrollY="+(scrollY-oldScrollY));
                //上滑
                if(scrollY-oldScrollY > 0 ){  //向上滑
                    Log.i("pcj", "onScrollChange: 向上滑");

                    if(ll_news_detail_news_content.getHeight() <= scrollY+news_detail_nestedScrollView.getHeight()&&!isBottomBarShow){  //滑到底部
                        Log.i("pcj", "onScrollChange: 滑到底");
                        rl_newsDetail_bottomBar.animate().cancel();
                        rl_newsDetail_bottomBar.animate().translationY(0).start();
                        isBottomBarShow = true;
                    }else if(isBottomBarShow){
                        rl_newsDetail_bottomBar.animate().cancel();
                        rl_newsDetail_bottomBar.animate().translationY(rl_newsDetail_bottomBar.getHeight()).start();
                        isBottomBarShow =false;
                    }
                }else if(scrollY-oldScrollY < 0 && !isBottomBarShow){  //向下滑
                    Log.i("pcj", "onScrollChange: 向下滑");
                    rl_newsDetail_bottomBar.animate().cancel();
                    rl_newsDetail_bottomBar.animate().translationY(0).start();
                    isBottomBarShow = true;
                }

            }
        });

        ib_newsDetail_collect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Drawable icon_collect_drawable = getResources().getDrawable(R.mipmap.icon_collect);
                if(isCollected){    //已收藏
                    ib_newsDetail_collect.setImageDrawable(tintDrawable(icon_collect_drawable, ColorStateList.valueOf(getResources().getColor(R.color.icon_origin))));
                    isCollected=false;
                }else { //未收藏
                    ib_newsDetail_collect.setImageDrawable(tintDrawable(icon_collect_drawable, ColorStateList.valueOf(getResources().getColor(R.color.colorPrimary))));
                    isCollected=true;
                }
            }
        });


    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_news_detail,menu);
        if (menu != null) {
            if (menu.getClass() == MenuBuilder.class) {
                try {
                    Method m = menu.getClass().getDeclaredMethod("setOptionalIconsVisible", Boolean.TYPE);
                    m.setAccessible(true);
                    m.invoke(menu, true);
                } catch (Exception e) {

                }
            }
        }
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()){
            case android.R.id.home:
                finish();
        }
        return super.onOptionsItemSelected(item);
    }

    private class MyWebViewClient extends WebViewClient {
        //ProgressDialog progressDialog = new ProgressDialog();
        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
            progress_layer.setAlpha(1f);
            //progress_layer.setVisibility(View.VISIBLE);
            getWindow().setFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE,WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            imgReset();//重置webview中img标签的图片大小
            // html加载完成之后，添加监听图片的点击js函数
            addImageClickListner();
            progress_layer.animate().setDuration(500).alpha(0f).start();
           // progress_layer.setVisibility(View.GONE);
            getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
        }


        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            if(!url.startsWith("tbopen"))
                view.loadUrl(url);
            return true;
        }
        private void imgReset() {
            webView.loadUrl("javascript:(function(){" +
                    "var objs = document.getElementsByTagName('img'); " +
                    "for(var i=0;i<objs.length;i++)  " +
                    "{"
                    + "var img = objs[i];   " +
                    "    img.style.maxWidth = '100%'; img.style.height = 'auto'; img.style.align='center' " +
                    "}" +
                    "})()");
        }
        private void addImageClickListner() {
            webView.loadUrl("javascript:(function(){" +
                    "var objs = document.getElementsByTagName(\"img\"); " +
                    "for(var i=0;i<objs.length;i++)  " +
                    "{"
                    + "    objs[i].onclick=function()  " +
                    "    {  "
                    + "        window.imagelistner.openImage(this.src);  " +
                    "    }  " +
                    "}" +
                    "})()");
        }
    }
    public static class JavaScriptInterface {

        private Context context;

        public JavaScriptInterface(Context context) {
            this.context = context;
        }

        //点击图片回调方法
        //必须添加注解,否则无法响应
        @JavascriptInterface
        public void openImage(String img) {
            Log.i("TAG", "响应点击事件!");
            Intent intent = new Intent();
            intent.putExtra("image", img);
            //intent.setClass(context, BigImageActivity.class);//BigImageActivity查看大图的类，自己定义就好
            Toast.makeText(context,img,Toast.LENGTH_SHORT).show();
            context.startActivity(intent);
        }
    }
}
